import django_filters

from goods.models import Goods


class GoodsFilter(django_filters.rest_framework.FilterSet):
    # 定义过滤的字段
    typeid = django_filters.CharFilter('categoryid')
    # 如果过滤的字段和数据库字段一致，则CharFilter中字段可不定义
    childcid = django_filters.CharFilter(method='get_childcid')
    order_rule = django_filters.CharFilter(method='rule')

    class Meta:
        model = Goods
        fields = ['typeid', 'childcid']

    def get_childcid(self, queryset, name, value):
        if value == '0':
            # 如果childcid为0，则表示不做子分类的过滤
            return queryset
        else:
            # 如果childcid不为0，则过滤子分类的信息
            return queryset.filter(childcid=value)

    def rule(self, queryset, name, value):
        if value == '1':
            return queryset.order_by('price')
        elif value == '2':
            return queryset.order_by('-price')
        elif value == '3':
            return queryset.order_by('productnum')
        else:
            # value为4或0的时候，按照销量降序排序
            return queryset.order_by('-productnum')